<template>
    <div class="app-container calendar-list-container" v-loading="loading" element-loading-text="正在导出数据">
    <!-- filter 条件查询 -->
    <div class="filter-container">
        <el-input
            @keyup.enter.native="getData"
            clearable
            v-model="param.userName"
            class="filter-item searchMsg"
            :placeholder="'请输入姓名'"
        ></el-input>

        <el-input
            @keyup.enter.native="getData"
            clearable
            v-model="param.jobNumber"
            class="filter-item searchMsg"
            :placeholder="'请输入工号'"
        ></el-input>

        <el-select 
              clearable 
              @keyup.enter.native="getData" 
              v-model="param.departmentName" 
              @focus="getDepartInfo" 
              class="filter-item searchMsg" 
              placeholder="请输入员工部门" >
          <el-option :value="item" :label="item" v-for="(item,index) in this.departList" :key="index"/>
        </el-select>

        <el-date-picker
        :clearable="false"
        v-model="dateOptions"
        type="datetimerange"
        value-format="yyyy-MM-dd HH:mm:ss"
        format="yyyy-MM-dd HH:mm:ss"
        :picker-options="pickerOptions"
        range-separator="至"
        start-placeholder="请选择开始时间"
        end-placeholder="结束时间"
        align="right"
        style="margin-right:15px;"
        />

      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="getData">搜索</el-button>

    </div>
    
    <!-- table 表格 -->
    <el-table :data="tableInfo" v-loading="loadingList" element-loading-text="给我一首歌的时间" stripe border fit highlight-current-row style="width: 100%">
        <el-table-column label="序号" type="index" align="center" width="80"/>
        <el-table-column label="工号" prop='job_number' align="center"/>
        <el-table-column label="姓名" prop='user_name' align="center"/>
        <el-table-column label="部门" prop='department_name' align="center"/>
        <el-table-column label="工时完成率" prop='manHour' align="center"/>
        <el-table-column label="品质系数" prop='quality' align="center" width="80"/>
        <el-table-column label="上司评价" prop='leadership' align="center"/>
        <el-table-column label="工时完成率得分(40%)" prop='manHour100' align="center"/>
        <el-table-column label="质量得分(40%)" prop='quality100' align="center" width="120"/>
        <el-table-column label="上司评价得分(20%)" prop='leadership100' align="center"/>
        <el-table-column label="关键事项加减分" prop='keyIssues' align="center"/>
        <el-table-column label="绩效总得分" prop='total_points' align="center"/>
        <el-table-column label="时间" prop='create_time' align="center" width="120"/>
        <el-table-column fixed="right" label="排名" prop='ranking' align="center"/>
        <el-table-column fixed="right" label="备注" prop='remarks' align="center"/>
    </el-table>
   
   <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[5,10, 20, 30, 40, 100, 300, 500]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

     <el-divider></el-divider>

    <el-button type="success" size="small" @click="hExportExcel">导出数据Excel</el-button>

  </div>
</template>

<script>
import { performanceAssessment } from '@/api/performance.js'
import { getDepartList } from '@/api/user'
export default {
    name: 'perAppraisal',
    data() {
        return {
            total: 0,                           //数据的总数
            listQuery: {
                page: 1,                          //页码
                limit: 10,                        //每页显示的数据条数
            },
            param: {
                jobNumber: '',                    //工号
                userName: '',                     //姓名
                departmentName: ''                //部门
            },
            tableInfo: [],
            loadingList: false,
            loading: false,
            departList: {},                     //部门下拉选择
            pickerOptions: {
                shortcuts: [{
                  text: '最近一周',
                  onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                    picker.$emit('pick', [start, end]);
                  }
                }, {
                  text: '最近一个月',
                  onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                    picker.$emit('pick', [start, end]);
                  }
                }, {
                  text: '最近三个月',
                  onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                    picker.$emit('pick', [start, end]);
                  }
                }]
            },
            dateOptions: this.getNowTime()
        }
    },
    methods: {
    transformDat(res) {
      const mapInfo = {
        index:'序号',
        job_number: '工号',
        user_name: '姓名',
        department_name: '部门',
        manHour:'工时完成率',
        quality: '品质系数',
        leadership: '上司评价',
        manHour100: '工时完成率得分(40%)',
        quality100: '质量得分(40%)',
        leadership100: '上司评价得分(20%)',
        keyIssues: '关键事项加减分',
        total_points: '绩效总得分',
        create_time: '时间',
        ranking: '排名',
        remarks: '备注'
      }
      // 对data进行格式化
      // 取出所有的属性名
      const props = Object.keys(res[0]) // ['id','']
      console.log(props)
      // 将属性名从英文转为中文
      const header = props.map(zhkey => mapInfo[zhkey])
      console.log('中文的表头', header)
      // const data=[['xxxx','总裁办'，'13800000']]
      const data = res.map(obj => Object.values(obj))
      return { header, data }
    },
    // 导出excel
    async hExportExcel() {
      this.loading = true
      let query = Object.assign({},this.listQuery)
      if(this.dateOptions.length) {
        query.startTime = this.dateOptions[0]
        query.endTime = this.dateOptions[1]
      }
      if(this.param.jobNumber){ query.jobNumber = this.param.jobNumber}
      if(this.param.userName){ query.userName = this.param.userName}
      if(this.param.departmentName){ query.departmentName = this.param.departmentName}
      query.page = 1
      query.limit = 10000
      console.log('%c导出excel传的参数query:','color:green;font-size:16px;')
      console.log(query)

      let arr = await performanceAssessment(query)
      let dateString = this.dateOptions.length?this.dateOptions[0] + '-' + this.dateOptions[1]:''
      let departmentNameString = this.listQuery.departmentName?this.listQuery.departmentName + '-':''
      let nameString = dateString + departmentNameString
      if(!arr.data.list.length) return this.$message.error('导出数据为空！')
      const { header, data } = this.transformDat(this.setSort(arr.data.list))
        import('@/vendor/Export2Excel').then(excel => {
            // excel表示导入的模块对象
            console.log(excel)
            excel.export_json_to_excel({
                header, // 表头 必填
                data, // 具体数据 必填
                filename: nameString + '绩效考核数据' + 'excel', // 文件名称
                autoWidth: true, // 宽度是否自适应
                bookType: 'xlsx' // 生成的文件类型
            })
        })
      this.loading = false
    },
    // 排序函数
    setSort(arr){
      let newArr = JSON.parse(JSON.stringify(arr))
      let arr1 = []
      newArr.forEach((item,index)=>{
        let obj = {
          index: index+1,
          job_number: item.job_number,
          user_name: item.user_name,
          department_name: item.department_name,
          manHour: item.manHour,
          quality: item.quality,
          leadership: item.leadership,
          manHour100: item.manHour100,
          quality100: item.quality100,
          leadership100: item.leadership100,
          keyIssues: item.keyIssues,
          total_points: item.total_points,
          create_time: item.create_time,
          ranking: item.ranking,
          remarks: ''
        }
        arr1.push(obj)
      })
      return arr1
    },
    // 搜索按钮绑定的函数，向服务器发送表单数据
    // 所有传输的表单字段都不是必须的，按需查询
    async handleFilter(param) {
      this.loadingList = true
      let query = Object.assign({},this.listQuery)
      if(this.dateOptions.length) {
        query.startTime = this.dateOptions[0]
        query.endTime = this.dateOptions[1]
      }
      if(this.param.jobNumber){ query.jobNumber = this.param.jobNumber}
      if(this.param.userName){ query.userName = this.param.userName}
      if(this.param.departmentName){ query.departmentName = this.param.departmentName}
      // 用来判断查询的条件是否为空，当不为空时，则返回到首页，也就是第一页
      if(param=='1') {
		    query.page = 1
        this.listQuery.page = 1
      } else {
        console.log('搜索内容不为空')
      }
      console.log('query',query)
      let {data} =await performanceAssessment(query)
      this.tableInfo = data.list
      this.total = data.count
      this.loadingList = false
    },
    //初始默认执行(重点)
    getNowTime() {
      let dateTime = +new Date()+8*3600*1000
      const start = new Date(dateTime - 3600 * 1000 * 24 * 30)
        .toISOString()
        .replace('T', ' ')
        .split('.')[0] //默认开始时间7天前
      const end = new Date(dateTime)
        .toISOString()
        .replace('T', ' ')
        .split('.')[0]//默认结束时间当前时间
      console.log([start, end])
      return [start, end]
    },
    // 获取部门下拉框数据
    async getDepartInfo() {
      let {data} = await getDepartList()
      this.departList = data
    }, 
    // table表单下方的页码组件改变每页显示的数据条数
     handleSizeChange(val) {
      this.listQuery.limit = val
      this.handleFilter()
    },
    // table表单下方的页码组件改变页面
     handleCurrentChange(val) {
      this.listQuery.page = val
      this.handleFilter()
    },
    getData() {
      this.listQuery.page = 1
      this.listQuery.limit = 10
      this.handleFilter()
    },
  },
  // 进入页面获取table信息
  mounted() {
    this.handleFilter()
  }
}
</script>

<style>

.operation_show {
  display: none;
}
.el-table__body tr:hover > td .operation_show {
  display: block;
}
.searchMsg{
  width: 150px;
  margin-right:15px;
}
</style>